<template>
    <div>
        <Form :label-width="100" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form2">
                <i-col span="8">
                    <FormItem label="投入年份：">
                        <DatePicker type="year" placeholder="请选择安全投入年份" style="width: 100%" v-model="formInline.selectYear"></DatePicker>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <FormItem label="当前公司：">
                        <orgDom ref="orgDom" @setOrgInfo="setOrgName" :orgInfo="{name: formInline.orgName}"></orgDom>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                    </div>
                </i-col>
            </Row>
        </Form>
        <Row :gutter="16" >
            <i-col>
                <div style="float: right;">
                    <RadioGroup v-model="viewType" type="button">
                        <Radio label="list">列表</Radio>
                        <Radio label="pie" >饼图</Radio>
                        <Radio label="bar" >柱图</Radio>
                    </RadioGroup>
                </div>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
               :data="infos" :height="tableHeight" highlight-row stripe size="small" v-if="viewType == 'list'" :summary-method="handleSummary" show-summary sum-text="合计"></Table>
        <div ref='pieDiv' :style="{width: '100%'}" v-if="viewType == 'pie'"></div>
        <div ref='barDiv' :style="{width: '100%'}"  v-if="viewType == 'bar'"></div>
    </div>
</template>

<script>
    import echarts from 'echarts';
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '../../../api'
    import orgDom from "@/components/input-org.vue";

    export default {
        name: "safetyProductionBar",
        components:{
            orgDom,
        },
        data(){
            return {
                loading: false,
                viewType: 'list',
                formInline: {
                    selectYear: new Date(),
                    orgId: sessionStorage('userId').getObject('userId').companyId,
                    orgName: sessionStorage('userId').getObject('userId').companyName,
                },
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        align: 'center',
                        key: 'index',
                        width: 80,
                        fixed: 'left',
                    },
                    {
                        title: '项目',
                        align: 'center',
                        key: 'codingName',
                        minWidth: 220,
                        fixed: 'left',
                    },
                    {
                        title: '一月',
                        align: 'center',
                        key: 'january',
                        minWidth: 100,
                    },
                    {
                        title: '二月',
                        align: 'center',
                        key: 'february',
                        minWidth: 100,
                    },
                    {
                        title: '三月',
                        align: 'center',
                        key: 'march',
                        minWidth: 100,
                    },
                    {
                        title: '四月',
                        align: 'center',
                        key: 'april',
                        minWidth: 100,

                    },
                    {
                        title: '五月',
                        align: 'center',
                        key: 'may',
                        minWidth: 100,

                    },
                    {
                        title: '六月',
                        align: 'center',
                        key: 'june',
                        minWidth: 100,
                    },
                    {
                        title: '七月',
                        align: 'center',
                        key: 'july',
                        minWidth: 100,
                    },
                    {
                        title: '八月',
                        align: 'center',
                        key: 'august',
                        minWidth: 100,
                    },
                    {
                        title: '九月',
                        align: 'center',
                        key: 'september',
                        minWidth: 100,
                    },
                    {
                        title: '十月',
                        align: 'center',
                        key: 'october',
                        minWidth: 100,

                    },
                    {
                        title: '十一月',
                        align: 'center',
                        key: 'november',
                        minWidth: 100,

                    },
                    {
                        title: '十二月',
                        align: 'center',
                        key: 'december',
                        minWidth: 100,
                    },
                    {
                        title: '合计金额（万元）',
                        align: 'center',
                        key: 'sumNum',
                        minWidth: 140,
                    },
                ],
                infos: [],
                tableHeight: '',

            }
        },
        watch: {
            "viewType": function(qw,er){
                if(qw == 'bar'){
                    setTimeout(() => {
                        this.drawBar();
                    }, 100);
                }else if(qw == 'pie'){
                    setTimeout(() => {
                        this.drawPie();
                    }, 100);
                }
            }
        },
        mounted(){
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            // this.selectCodingSort();
            this.query();
            setTimeout(() => {
                this.$refs.orgDom.setCurrentOrg();
            }, 300);
        },
        methods: {
            query(){
                // let container = echarts.init(this.$refs.barDiv);
                // let pieDiv = echarts.init(this.$refs.pieDiv);
                // let option = this.getBarOption();
                // let pieOption = this.getPieOption();
                // pieOption.title.text = sessionStorage('userId').getObject('userId').companyName;
                // option.title.text = sessionStorage('userId').getObject('userId').companyName;

                let data = {
                    orgId: sessionStorage('userId').getObject('userId').companyId
                };
                this.loading = true;
                this.formInline.year = new Date(this.formInline.selectYear).getFullYear();
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.safetyProduction + '/count/company', {
                    params: data
                }).then(function(res){
                    // if(res.data.data!= undefined){
                    //     //柱状图
                    //     res.data.data.forEach(item=>{
                    //         option.series[0].data.push(item['sumNum']);
                    //         pieOption.series[0].data.push({value: item['sumNum'], name: item['codingName']})
                    //     })
                    // }
                    // //柱状图设置
                    // container.setOption(option);
                    // container.resize({height: (this.tableHeight + 10) +'px', width: window.innerWidth - 260 + 'px'});
                    // //饼图设置
                    // pieDiv.setOption(pieOption);
                    // pieDiv.resize({height: (this.tableHeight + 10) +'px', width: window.innerWidth - 260 + 'px'});
                    //列表
                    this.infos = res.data.data;
                    if(this.viewType == 'bar'){
                        this.drawBar();
                    }else if(this.viewType == 'pie'){
                        this.drawPie();
                    }
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            cancel(){
                this.formInline = {
                    selectYear: new Date(),
                    orgId: sessionStorage('userId').getObject('userId').companyId,
                    orgName: sessionStorage('userId').getObject('userId').companyName,
                }
                this.query();
            },
            setOrgName(data){
                this.formInline.orgId = data.orgId;
            },
            selectCodingSort(){
                this.$http.get(Api.queryCodeDetailBySortId +'/PRO-00001',{params:{}}).then((res) => {
                    res.data.data.forEach(item=>{
                        this.option.xAxis.data.push(item.codingName);
                    })
                })
            },
            getPieOption(){
                return {
                    title: {
                        text: 'Referer of a Website',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            name: '项目',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            center: ['75%', '50%'],
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '16',
                                    fontWeight: 'bold',
                                    color: 'black'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: []
                        }
                    ]
                }
            },
            getBarOption(){
                return {
                    title: {
                        text: '',
                        left: 'center'
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: [],
                        axisLabel: {
                            interval: 0,
                            formatter:function(value){
                                var str = "";
                                var num = 5; //每行显示字数
                                var valLength = value.length; //该项x轴字数
                                var rowNum = Math.ceil(valLength / num); // 行数
                                if(rowNum > 1) {
                                    for(var i = 0; i < rowNum; i++) {
                                        var temp = "";
                                        var start = i * num;
                                        var end = start + num;
                                        temp = value.substring(start, end) + "\n";
                                        str += temp;
                                    }
                                    return str;
                                } else {
                                    return value;
                                }
                            }
                        }
                    },
                    yAxis: {
                        type: 'value',
                    },
                    series: [
                        {
                            data: [],
                            type: 'bar',
                            showBackground: true,
                            backgroundStyle: {
                                color: 'rgba(180, 180, 180, 0.2)'
                            },
                            label: {
                                show: true,
                                position: 'inside'
                            },
                        }
                    ]
                }
            },
            drawBar(){
                let container = echarts.init(this.$refs.barDiv);
                container.clear();
                let option = this.getBarOption();
                option.title.text = sessionStorage('userId').getObject('userId').companyName;
                this.infos.forEach(item=>{
                    option.xAxis.data.push(item['codingName']);
                    option.series[0].data.push(item['sumNum']);
                })
                container.setOption(option);
                container.resize({height: (this.tableHeight + 52) +'px', width: window.innerWidth - 260 + 'px'});
            },
            drawPie(){
                let pieDiv = echarts.init(this.$refs.pieDiv);
                pieDiv.clear();
                let pieOption = this.getPieOption();
                pieOption.title.text = sessionStorage('userId').getObject('userId').companyName;
                this.infos.forEach(item=>{
                    pieOption.series[0].data.push({value: item['sumNum'], name: item['codingName']})
                })
                pieDiv.setOption(pieOption);
                pieDiv.resize({height: (this.tableHeight + 52) +'px', width: window.innerWidth - 260 + 'px'});
            },
            handleSummary ({ columns, data }) {
                const sums = {};
                columns.forEach((column, index) => {
                    const key = column.key;
                    if (index === 0) {
                        sums[key] = {
                            key,
                            value: '合计'
                        };
                        return;
                    }
                    const values = data.map(item => Number(item[key]));
                    if (!values.every(value => isNaN(value))) {
                        const v = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[key] = {
                            key,
                            value: v.toFixed(6)
                        };
                    } else {
                        sums[key] = {
                            key,
                            value: ''
                        };
                    }
                });

                return sums;
            },
        }
    }
</script>
<style scoped>
</style>
